<template>
  <div class="coze-chat-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <span class="status-text">{{ getCurrentTime() }}</span>
      <div class="status-icons">
        <span class="icon">📶</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 头部导航 -->
    <div class="chat-header">
      <button class="back-btn" @click="$router.back()">←</button>
      <h2 class="header-title">Coze 对话</h2>
      <div class="header-right">
        <button class="header-btn new-btn" @click="createNewConversation" title="新建对话">
          <span class="btn-icon">➕</span>
          <span class="btn-text">新建</span>
        </button>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <!-- 欢迎消息（只在没有历史消息时显示） -->
        <div v-if="messages.length === 0" class="message-item bot-message">
          <div class="avatar bot-avatar">🤖</div>
          <div class="message-content">
            <div class="message-bubble bot-bubble">
              <p>您好！我是 Coze AI 助手，有什么可以帮助您的吗？</p>
            </div>
            <div class="message-time">{{ getCurrentTime() }}</div>
          </div>
        </div>

        <!-- 用户消息列表 -->
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message-item', message.type === 'user' ? 'user-message' : 'bot-message']"
        >
          <div v-if="message.type === 'bot'" class="avatar bot-avatar">🤖</div>
          <div class="message-content">
            <div :class="['message-bubble', message.type === 'user' ? 'user-bubble' : 'bot-bubble']">
              <p>{{ message.content }}</p>
            </div>
            <div class="message-time">{{ message.time }}</div>
          </div>
          <div v-if="message.type === 'user'" class="avatar user-avatar">👤</div>
        </div>

        <!-- 加载中提示 -->
        <div v-if="loading" class="message-item bot-message">
          <div class="avatar bot-avatar">🤖</div>
          <div class="message-content">
            <div class="message-bubble bot-bubble typing">
              <span></span><span></span><span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <input 
          v-model="inputText"
          type="text"
          placeholder="输入您的问题..."
          class="message-input"
          @keyup.enter="sendMessage"
        />
        <button class="send-btn" @click="sendMessage" :disabled="!inputText.trim() || loading">
          <span v-if="!loading">发送</span>
          <span v-else>...</span>
        </button>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <div class="nav-item" @click="$router.push('/feed')">
        <span class="nav-icon">🏠</span>
        <span class="nav-label">首页</span>
      </div>
      <div class="nav-item">
        <span class="nav-icon">🛒</span>
        <span class="nav-label">购物</span>
      </div>
      <div class="nav-item highlight" @click="$router.push('/publish')">
        <span class="nav-icon-blue">+</span>
        <span class="nav-label">发布</span>
      </div>
      <div class="nav-item">
        <span class="nav-icon">💬</span>
        <span class="nav-label">消息</span>
      </div>
      <div class="nav-item" @click="$router.push('/customer-service')">
        <span class="nav-icon">🛟</span>
        <span class="nav-label">客服</span>
      </div>
      <div class="nav-item" @click="$router.push('/profile')">
        <span class="nav-icon">👤</span>
        <span class="nav-label">我的</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import apiClient from '@/api/axios'

const router = useRouter()
const messages = ref([])
const inputText = ref('')
const loading = ref(false)
const messagesContainer = ref(null)
const currentConversationId = ref(null) // 当前对话ID

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

/**
 * 发送消息（使用 Coze 对话系统）
 * 
 * 功能：
 * - 调用 /api/coze/chat 接口发送消息
 * - 使用 Coze Bot 进行智能对话
 * - 支持多轮对话
 */
const sendMessage = async () => {
  // 校验：消息不能为空，且当前没有正在发送的消息
  if (!inputText.value.trim() || loading.value) return

  // ============ 构建用户消息对象 ============
  const userMessage = {
    type: 'user',
    content: inputText.value.trim(),
    time: getCurrentTime()
  }

  // 添加到消息列表（立即显示，提升用户体验）
  messages.value.push(userMessage)
  const question = inputText.value.trim()
  inputText.value = ''
  loading.value = true

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // ============ 调用 Coze 对话 API ============
  try {
    // 获取用户ID（如果有登录用户，使用用户ID；否则使用默认值）
    const userId = localStorage.getItem('user_id') || 'default_user'
    
    const response = await apiClient.post('/coze/chat', {
      message: question,
      user_id: userId,
      conversation_id: currentConversationId.value // 如果已有对话，使用现有对话ID
    })

    if (response.data.success) {
      // 更新当前对话ID（如果是新创建的对话）
      if (response.data.conversation_id && !currentConversationId.value) {
        currentConversationId.value = response.data.conversation_id
        // 保存到 localStorage
        localStorage.setItem('current_coze_conversation_id', currentConversationId.value)
      }

      // 添加助手回复
      const botMessage = {
        type: 'bot',
        content: response.data.message,
        time: getCurrentTime()
      }
      messages.value.push(botMessage)
      
      console.log('[Coze对话] 消息发送成功，对话ID:', response.data.conversation_id)
      if (response.data.token_usage) {
        console.log('[Coze对话] Token使用:', response.data.token_usage)
      }
    } else {
      // 发送失败，显示错误消息
      const botMessage = {
        type: 'bot',
        content: response.data.error || '发送失败，请稍后重试',
        time: getCurrentTime()
      }
      messages.value.push(botMessage)
    }
    
    loading.value = false
    await nextTick()
    scrollToBottom()

  } catch (error) {
    console.error('[Coze对话] 发送消息失败:', error)
    const errorMsg = error.response?.data?.detail || error.message || '网络错误，请稍后重试'
    
    const botMessage = {
      type: 'bot',
      content: `抱歉，发送失败：${errorMsg}`,
      time: getCurrentTime()
    }
    messages.value.push(botMessage)
    loading.value = false
    await nextTick()
    scrollToBottom()
  }
}

/**
 * 创建新对话（清空当前对话）
 */
const createNewConversation = async () => {
  try {
    // 清空当前对话ID
    currentConversationId.value = null
    localStorage.removeItem('current_coze_conversation_id')
    
    // 清空消息列表（只保留欢迎消息）
    messages.value = []
    
    console.log('[Coze对话] 已创建新对话')
    
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('[Coze对话] 创建新对话失败:', error)
    alert('创建新对话失败，请稍后重试')
  }
}

/**
 * 初始化对话
 */
const initConversation = async () => {
  try {
    // 尝试从 localStorage 获取上次的对话ID（可选）
    const savedConversationId = localStorage.getItem('current_coze_conversation_id')
    if (savedConversationId) {
      currentConversationId.value = savedConversationId
      console.log('[Coze对话] 已恢复对话ID:', savedConversationId)
    } else {
      // 如果没有保存的对话ID，将在第一次发送消息时自动创建
      console.log('[Coze对话] 准备开始新对话')
    }
  } catch (error) {
    console.error('[Coze对话] 初始化对话失败:', error)
    // 即使失败，也允许用户继续使用
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// ============ 组件生命周期 ============
onMounted(async () => {
  // 页面加载时：初始化对话
  scrollToBottom()
  await initConversation()
})

</script>

<style scoped>
.coze-chat-container {
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 70px;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background: white;
  font-size: 12px;
}

.status-icons {
  display: flex;
  gap: 5px;
}

/* 头部导航 */
.chat-header {
  background: white;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
  color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
  padding: 6px 10px;
  border: none;
  border-radius: 18px;
  font-size: 11px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-btn:active {
  transform: scale(0.95);
}

.new-btn {
  background: #ffc107;
  color: #333;
}

.new-btn:hover {
  background: #e0a800;
  box-shadow: 0 3px 6px rgba(255, 193, 7, 0.3);
}

.btn-icon {
  font-size: 13px;
  line-height: 1;
}

.btn-text {
  font-size: 11px;
  line-height: 1;
}

/* 聊天容器 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background: #f5f5f5;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
  gap: 10px;
}

.user-message {
  flex-direction: row-reverse;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
}

.bot-avatar {
  background: #e3f2fd;
}

.user-avatar {
  background: #007AFF;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.user-message .message-content {
  align-items: flex-end;
}

.bot-message .message-content {
  align-items: flex-start;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
}

.user-bubble {
  background: #007AFF;
  color: white;
  border-bottom-right-radius: 4px;
}

.bot-bubble {
  background: white;
  color: #333;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 4px;
}

.message-time {
  font-size: 11px;
  color: #999;
  padding: 0 5px;
}

/* 输入动画 */
.typing {
  display: flex;
  gap: 4px;
  align-items: center;
}

.typing span {
  width: 8px;
  height: 8px;
  background: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 输入区域 */
.input-area {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 15px;
  background: white;
  border-top: 1px solid #f0f0f0;
}

.message-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.message-input:focus {
  border-color: #007AFF;
}

.send-btn {
  padding: 10px 20px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.send-btn:hover:not(:disabled) {
  background: #0056b3;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 6px 0;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  font-size: 11px;
  color: #666;
  cursor: pointer;
  position: relative;
  flex: 1;
}

.nav-item.active {
  color: #007AFF;
}

.nav-icon {
  font-size: 18px;
}

.nav-icon-blue {
  width: 36px;
  height: 36px;
  background: #007AFF;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}

.nav-label {
  font-size: 9px;
}

.highlight .nav-label {
  color: #007AFF;
}
</style>

